"""
    如果允许进入聊天

"""
import os
from socket import *

ADDR = ('0.0.0.0', 8888)
# 存储用户信息
user = {}


def do_login(s, name, addr):
    if name in user or '管理员' in name:
        s.sendto("\n该用户已存在".encode(), addr)
        return
    s.sendto(b'OK', addr)
    # 通知其他人
    msg = '\n欢迎%s进入聊天室' % name
    for i in user:
        s.sendto(msg.encode(), user[i])
    # 将用户加入
    user[name] = addr


# 聊天
def do_chat(s, name, text):
    msg = "\n%s : %s" % (name, text)
    for i in user:
        if i != name:
            s.sendto(msg.encode(), user[i])


# 退出
def do_quit(s, name):
    msg = '%s退出了聊天室' % name
    for i in user:
        if i != name:
            s.sendto(msg.encode(), user[i])
        else:
            s.sendto(b'EXIT', user[i])
    # 将用户删除
    del user[name]


def do_request(s):
    while True:
        data, addr = s.recvfrom(1024)
        print(data.decode())
        msg = data.decode().split(' ')
        # 区分请求类型
        if msg[0] == 'L':
            do_login(s, msg[1], addr)
        elif msg[0] == 'C':
            do_chat(s, msg[1], ' '.join(msg[2:]))
        elif msg[0] == 'Q':
            if msg[1] not in user:
                s.sendto(b'EXIT', addr)
                continue
            do_quit(s, msg[1])


# 创建网络连接
def main():
    s = socket(AF_INET, SOCK_DGRAM)
    s.bind(ADDR)
    pid = os.fork()
    if pid < 0:
        return
    elif pid == 0:
        while True:
            msg = input('管理员消息：')
            msg = "C 管理员消息 " + msg
            # 给父进程发送消息
            s.sendto(msg.encode(), ADDR)
    else:
        # 请求处理,处理客户端请求
        do_request(s)


if __name__ == '__main__':
    main()
